import { InjectRepository } from '@nestjs/typeorm';
import { HttpException, Injectable } from '@nestjs/common';
import { CreateRoleDto } from './dto/create-role.dto';
import { UpdateRoleDto } from './dto/update-role.dto';
import { Role } from './entities/role.entity';
import { Repository } from 'typeorm';
@Injectable()
export class RoleService {
  constructor(
    @InjectRepository(Role) private readonly role: Repository<Role>,
  ) {}
  create(createRoleDto: any) {
    console.log('createRoleDto: ', createRoleDto);
    // console.log('createRoleDto: ', createRoleDto);
    // const { type } = createRoleDto;
    // const role = new Role();
    // this.role.save(role);
    // this.role.find({where: })
    return null;
  }

  async findAll(req: any) {
    const { page = 1, pageSize = 5, ...rest } = req;
    const qb = await this.role.createQueryBuilder('role');

    const total = await qb.getCount();
    qb.limit(pageSize);
    qb.offset((page - 1) * pageSize);
    const list = await qb.getMany();
    console.log('qb', list, total);
    return { list, total };
  }

  findOne(id: number) {
    return `This action returns a #${id} role`;
  }

  async update(updateRoleDto) {
    const { id, ...rest } = updateRoleDto;
    const doc = await this.role.findOne({ where: { id } });
    if (!doc) {
      throw new HttpException('没有找到该id', 400);
    } else {
      const data = await this.role.merge(doc, rest);
      await this.role.save(data);
      return null;
    }
  }

  remove(id: number) {
    return `This action removes a #${id} role`;
  }
}
